package com.september.concurrent;

import java.net.UnknownHostException;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.Semaphore;

import com.google.code.morphia.Datastore;
import com.september.mongo.data.DataProvider;
import com.september.mongo.entities.City;
import com.september.mongo.entities.Province;
import com.september.prop.Properteer;

public class DupsHandlerThread  extends Thread implements IThread{

	private Semaphore semaphore;
	List<Province> provinceList;
	private Semaphore citySem;
	
	private String identifier = this.getClass().getName()+"\t"+this.getId();

	public DupsHandlerThread(List<Province> provList, Semaphore sem, Semaphore citySem) {

		this.semaphore = sem;
		this.provinceList = provList;
		this.citySem = citySem;
	}

	public void run() {
		try {
			semaphore.acquire();
			criticalCode();
			semaphore.release();
		} catch (InterruptedException e) {
			Properteer.getInstance().getLogger(DupsHandlerThread.class).error(e.getClass().getName(), e);
		} catch (UnknownHostException e) {
			Properteer.getInstance().getLogger(DupsHandlerThread.class).error(e.getClass().getName(), e);
		}

	}

	public void handleDups(List<City> cityList, Datastore ds) {
		if (cityList.size() == 0)
			return;
		List<String> reference = new LinkedList<String>();
		for (City city : cityList) {
			if (reference.contains(city.getName())) {
				ds.delete(city);
				Properteer.getInstance().getLogger(DupsHandlerThread.class).debug("Deleting " + city.getName() + "\t from "
						+ city.getProvince().getCode() + "\t"
						+ city.getRegion().getCode() + "\t"
						+ city.getNation().getCountry());
			} else {
				reference.add(city.getName());
			}
		}
	}

	private void criticalCode() throws UnknownHostException {

		Datastore ds = (new DataProvider()).getDatastore();

		try {
			log(identifier+"\tstarted");
			for (Province province : provinceList) {
				List<City> cityList = ds.find(City.class).field("province")
						.equal(province).asList();
				log(identifier+"\tCities: "+cityList.size());
				(new CityDupsHandlerThread(cityList, citySem)).start();
				
			}

		}

		catch (Exception e) {
			e.printStackTrace();
		}

	}

	public void log(String message) {
		Properteer.getInstance().getLogger(DupsHandlerThread.class).debug(message);
	}

}
